from django.shortcuts import render, get_object_or_404
from rest_framework import viewsets, status, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import ExerciseSet, Exercise, UserExerciseRecord, UserExerciseSetProgress
from .serializers import (
    ExerciseSerializer, ExerciseSetSerializer, ExerciseSetDetailSerializer,
    UserExerciseRecordSerializer, UserExerciseSetProgressSerializer,
    ImportQuestionsSerializer
)
from parser.models import ParsedQuestion
from documents.models import Document
from django.db import transaction
from django.utils import timezone
import logging

logger = logging.getLogger(__name__)

class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    自定义权限，只允许对象的创建者编辑它
    """
    def has_object_permission(self, request, view, obj):
        # 读取权限允许任何请求
        if request.method in permissions.SAFE_METHODS:
            return True
        
        # 写入权限只允许对象的创建者
        return obj.created_by == request.user

class ExerciseSetViewSet(viewsets.ModelViewSet):
    """练习集视图集"""
    queryset = ExerciseSet.objects.all()
    serializer_class = ExerciseSetSerializer
    permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly]
    
    def get_serializer_class(self):
        if self.action == 'retrieve':
            return ExerciseSetDetailSerializer
        return ExerciseSetSerializer
    
    def get_queryset(self):
        """允许按创建者筛选练习集"""
        queryset = ExerciseSet.objects.all()
        
        # 非公开的练习集只对创建者可见
        if not self.request.user.is_staff:
            queryset = queryset.filter(
                is_public=True
            ) | queryset.filter(
                created_by=self.request.user
            )
        
        # 按创建者筛选
        user_id = self.request.query_params.get('user_id')
        if user_id:
            queryset = queryset.filter(created_by_id=user_id)
        
        # 按标题搜索
        search = self.request.query_params.get('search')
        if search:
            queryset = queryset.filter(title__icontains=search)
        
        return queryset
    
    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)
    
    @action(detail=False, methods=['post'])
    def import_questions(self, request):
        """从解析的文档中导入题目创建练习集"""
        serializer = ImportQuestionsSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        
        document_id = serializer.validated_data['document_id']
        title = serializer.validated_data['title']
        description = serializer.validated_data.get('description', '')
        is_public = serializer.validated_data.get('is_public', False)
        
        try:
            # 获取文档
            document = get_object_or_404(Document, pk=document_id)
            
            # 获取文档中的题目
            questions = ParsedQuestion.objects.filter(document=document)
            
            if not questions.exists():
                return Response(
                    {'error': '该文档没有解析出题目'},
                    status=status.HTTP_400_BAD_REQUEST
                )
            
            # 创建练习集和练习题
            with transaction.atomic():
                # 创建练习集
                exercise_set = ExerciseSet.objects.create(
                    title=title,
                    description=description,
                    created_by=request.user,
                    is_public=is_public
                )
                
                # 创建练习题
                exercises = []
                for question in questions:
                    exercise = Exercise(
                        exercise_set=exercise_set,
                        content=question.content,
                        answer=question.answer,
                        question_type=question.question_type,
                        source_question=question
                    )
                    exercises.append(exercise)
                
                # 批量创建练习题
                Exercise.objects.bulk_create(exercises)
                
                # 返回创建的练习集
                serializer = ExerciseSetDetailSerializer(exercise_set)
                return Response(
                    {
                        'message': f'成功从文档导入{len(exercises)}个题目',
                        'exercise_set': serializer.data
                    },
                    status=status.HTTP_201_CREATED
                )
                
        except Exception as e:
            logger.error(f"导入题目错误: {str(e)}")
            return Response(
                {'error': f'导入题目失败: {str(e)}'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

class ExerciseViewSet(viewsets.ModelViewSet):
    """练习题视图集"""
    queryset = Exercise.objects.all()
    serializer_class = ExerciseSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        """允许按练习集筛选练习题"""
        queryset = Exercise.objects.all()
        
        # 按练习集筛选
        exercise_set_id = self.request.query_params.get('exercise_set_id')
        if exercise_set_id:
            queryset = queryset.filter(exercise_set_id=exercise_set_id)
        
        # 按题目类型筛选
        question_type = self.request.query_params.get('question_type')
        if question_type:
            queryset = queryset.filter(question_type=question_type)
        
        # 按难度筛选
        difficulty = self.request.query_params.get('difficulty')
        if difficulty:
            queryset = queryset.filter(difficulty=difficulty)
        
        return queryset

class UserExerciseRecordViewSet(viewsets.ModelViewSet):
    """用户练习记录视图集"""
    queryset = UserExerciseRecord.objects.all()
    serializer_class = UserExerciseRecordSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        """只返回当前用户的练习记录"""
        return UserExerciseRecord.objects.filter(user=self.request.user)
    
    def perform_create(self, serializer):
        """创建练习记录时自动设置用户"""
        serializer.save(user=self.request.user)
        
        # 更新用户的练习集进度
        exercise = serializer.instance.exercise
        exercise_set = exercise.exercise_set
        status = serializer.instance.status
        
        # 获取或创建用户的练习集进度
        progress, created = UserExerciseSetProgress.objects.get_or_create(
            user=self.request.user,
            exercise_set=exercise_set,
            defaults={
                'last_exercise': exercise,
                'started_at': timezone.now()
            }
        )
        
        # 如果不是跳过状态，则计入已完成题目
        if status != 'skipped':
            # 检查是否是第一次完成这道题
            if not UserExerciseRecord.objects.filter(
                user=self.request.user,
                exercise=exercise,
                status__in=['correct', 'incorrect']
            ).exclude(id=serializer.instance.id).exists():
                progress.completed_count += 1
            
            # 如果是正确的，则计入正确题目
            if status == 'correct':
                progress.correct_count += 1
        
        # 更新最后练习的题目和时间
        progress.last_exercise = exercise
        
        # 检查是否完成了所有题目
        if progress.completed_count >= exercise_set.questions_count:
            progress.is_completed = True
        
        progress.save()

class UserExerciseSetProgressViewSet(viewsets.ReadOnlyModelViewSet):
    """用户练习集进度视图集"""
    queryset = UserExerciseSetProgress.objects.all()
    serializer_class = UserExerciseSetProgressSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        """只返回当前用户的练习集进度"""
        return UserExerciseSetProgress.objects.filter(user=self.request.user)
    
    @action(detail=False, methods=['get'])
    def current(self, request):
        """获取当前用户的所有练习集进度"""
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
    
    @action(detail=True, methods=['post'])
    def reset(self, request, pk=None):
        """重置练习集进度"""
        progress = self.get_object()
        
        # 删除该练习集的所有练习记录
        UserExerciseRecord.objects.filter(
            user=request.user,
            exercise__exercise_set=progress.exercise_set
        ).delete()
        
        # 重置进度
        progress.completed_count = 0
        progress.correct_count = 0
        progress.is_completed = False
        progress.started_at = timezone.now()
        progress.save()
        
        serializer = self.get_serializer(progress)
        return Response(serializer.data)
